package lingnan.interceptor;

import lingnan.entity.User;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

@Component
public class LoginHandlerInterceptor implements HandlerInterceptor {
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        Object user = request.getSession().getAttribute("loginUser");
        System.out.println("afterCompletion----" + user + " ::: " + request.getRequestURL());
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        Object user = request.getSession().getAttribute("loginUser");
        System.out.println("postHandle----" + user + " ::: " + request.getRequestURL());
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        User user = (User) request.getSession().getAttribute("loginUser");
        System.out.println("preHandle----" + user + " ::: " + request.getRequestURL());


        HandlerMethod handlerMethod = (HandlerMethod) handler;
        // 获取用户token
        Method method = handlerMethod.getMethod();
        System.out.println("method:::"+method.getName());
        if(method.getName().equals("login"))
            return true;

        if (user == null) {
            request.setAttribute("loginError", "请先登录");
            // 获取request返回页面到登录页
            request.getRequestDispatcher("/user/toLogin").forward(request,response);
            return false;
        }
        if(user.getAccess()==1&&request.getRequestURL().indexOf("manage")!=-1){
            request.setAttribute("loginError", "无权限,不是管理员");
            // 获取request返回页面到登录页
            request.getRequestDispatcher("/user/toLogin").forward(request,response);
            return false;
        }
        return true;
    }



}